package com.blakequ.androidblemanager.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.blakequ.androidblemanager.R;
import com.blakequ.androidblemanager.containers.BluetoothLeDeviceStore;
import com.blakequ.androidblemanager.event.UpdateEvent;
import com.blakequ.androidblemanager.ui.MainPage;
import com.blakequ.androidblemanager.utils.BLEUtil;
import com.blakequ.androidblemanager.utils.BeaconModel;
import com.blakequ.androidblemanager.utils.BluetoothUtils;
import com.blakequ.bluetooth_manager_lib.device.BeaconType;
import com.blakequ.bluetooth_manager_lib.device.BeaconUtils;
import com.blakequ.bluetooth_manager_lib.device.ibeacon.IBeaconDevice;
import com.blakequ.bluetooth_manager_lib.scan.BluetoothScanManager;
import com.blakequ.bluetooth_manager_lib.scan.ScanOverListener;
import com.blakequ.bluetooth_manager_lib.scan.bluetoothcompat.ScanCallbackCompat;
import com.blakequ.bluetooth_manager_lib.scan.bluetoothcompat.ScanResultCompat;
import com.orhanobut.logger.Logger;
import com.tamsiree.rxkit.RxActivityTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MyServiceKeYiYunXing extends Service
{
//	private BluetoothLeDeviceStore mDeviceStore;
//	private BluetoothUtils mBluetoothUtils;
//	private BluetoothScanManager scanManager;
	List<BeaconModel> beaconModelList = new ArrayList<>();
	public static int NOTIFICATION_ID = 101;
	private static final String TAG = "MyService";
//	AlarmManager mAlarmManager = null;
//	PendingIntent mPendingIntent = null;
	public static boolean serviceIsLive = false;
	int count = 0;
//	SocketClient socketClient;
//	private UdpClientBiz udpClientBiz = new UdpClientBiz();//初始化客户端的，以便需要用的地方来使用
	Timer timer = new Timer();
	TimerTask timerTask = new TimerTask() {
		@Override
		public void run() {

			Log.d("BD-Debug", ++count + " : "+System.currentTimeMillis()+"");
//			BDManager.getInstance().sendTestData(MyService.this);
			submitBle();
		}
	};
//	public static List<BDModel> list = new ArrayList<>();
	@Override
	public void onCreate()
	{
		//start the service through alarm repeatly
//	    Intent intent = new Intent(getApplicationContext(), MyService.class);
//		mAlarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//		mPendingIntent = PendingIntent.getService(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
//		long now = System.currentTimeMillis();
//		mAlarmManager.setInexactRepeating(AlarmManager.RTC, now, 300, mPendingIntent);
//		Toast.makeText(getApplicationContext(), "onCreate!", Toast.LENGTH_SHORT).show();
		Log.i(TAG,"onCreate");
		// 获取服务通知
		Notification notification = createForegroundNotification();
		//将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
		startForeground(NOTIFICATION_ID, notification);
//		Toast.makeText(getApplicationContext(), "onStartCommand!", Toast.LENGTH_SHORT).show();
		Log.i(TAG,"onStartCommand");
		Log.d("BD-Debug", "onStartCommand");
//		BDManager.getInstance().onCreate(this);
		startTimer();
		//调用sendMsg方法，传入发送的消息与实现OnMsgReturnedListener
//		udpClientBiz.sendMsg("xiachao", new UdpClientBiz.OnMsgReturnedListener() {
//			@Override
//			public void onMsgReturned(String msg) {
//				//收到的信息
////				textView.append("server:"+msg+"\n");
//				Log.e("MyService","UDPClient:收到消息："+msg);
//				EventBus.getDefault().post(EventUWB.newBuilder().content(msg).build());
//			}
//
//			@Override
//			public void onError(Exception ex) {
//				ex.printStackTrace();//有错误打印出错误
//				Log.e("MyService","UDPClient:Error报错："+ex.toString());
//			}
//		});

		startSocket();
		EventBus.getDefault().register(this);
		initScan();
		super.onCreate();
	}

	public void startSocket() {
//		if (socketClient != null) {
//			socketClient.close();
//			socketClient = null;
//		}
//		if (socketClient == null) {
//			socketClient = new SocketClient();
//			socketClient.start();
//		}
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{

//		startTimer();
		return START_STICKY;
	}

	private void startTimer() {
		try {
			Log.d("BD-Debug", "startTimer");
//			if (timer != null) {
//				timer.cancel();
//			}
			timer.schedule(timerTask,0,20000);
			Log.d("BD-Debug", "startTimer success");
		} catch (Exception e) {
		    if (e != null) {
		        Log.e("",""+e.toString());
				Log.d("BD-Debug", "startTimer ： "+e.toString());
		    }
		}
	}


	/**
	 * 返回一个Binder对象
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return new MsgBinder();
	}


	@Override
	public void onDestroy() {
		Log.e("BD-Debug", "MyService - onDestroy");
		// 标记服务关闭
		serviceIsLive = false;
		// 移除通知
		stopForeground(true);
//		BDManager.getInstance().onDestroy();
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}



	/**
	 * 创建服务通知
	 */
	private Notification createForegroundNotification() {
		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		// 唯一的通知通道的id.
		String notificationChannelId = "notification_channel_id_01";

		// Android8.0以上的系统，新建消息通道
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			//用户可见的通道名称
			String channelName = "BLE定位服务";
			//通道的重要程度
			int importance = NotificationManager.IMPORTANCE_HIGH;
			NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, channelName, importance);
			notificationChannel.setDescription("BLE定位服务正在运行");
			//LED灯
			notificationChannel.enableLights(true);
			notificationChannel.setLightColor(Color.RED);
			//震动
//			if (!BuildConfig.DEBUG) {
//				notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
//				notificationChannel.enableVibration(true);
//			}
			if (notificationManager != null) {
				notificationManager.createNotificationChannel(notificationChannel);
			}
		}

		NotificationCompat.Builder builder = new NotificationCompat.Builder(this, notificationChannelId);
		//通知小图标
		builder.setSmallIcon(R.mipmap.ic_launcher);
		//通知标题
		builder.setContentTitle("BLE定位服务");
		//通知内容
		builder.setContentText("BLE定位正在运行");
		//设定通知显示的时间
		builder.setWhen(System.currentTimeMillis());
		//设定启动的内容
		Intent activityIntent = new Intent(this, MainPage.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		builder.setContentIntent(pendingIntent);

		//创建通知并返回
		return builder.build();
	}

	private void startBleScan() {

	}


	private  void startAlarmManager() {
		Intent intent =new Intent(this, MyServiceKeYiYunXing.class);
		PendingIntent sender=PendingIntent
				.getService(this, 0, intent, 0);
		AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
		alarm.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),5*1000,sender);
	}

	public class MsgBinder extends Binder {
		/**
		 * 获取当前Service的实例
		 * @return
		 */
		public MyServiceKeYiYunXing getService(){
			return MyServiceKeYiYunXing.this;
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEvent(UpdateEvent event){
//		startSocket();
	}


//	@Subscribe(threadMode = ThreadMode.MAIN)
//	public void onEvent(EventSwitch event){
//		if (socketClient != null) {
//			socketClient.close();
//			socketClient = null;
//		}
//		if (socketClient == null) {
//			socketClient = new SocketClient();
//			socketClient.start();
//		}
//	}


	private void initScan(){

	}


	private void submitBle() {
//		BLEUtil.getInstance().requestSubmit();
	}
}
